package com.MRSyc.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

///import org.apache.shiro.SecurityUtils;
//import org.apache.shiro.subject.Subject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.MRSyc.base.BaseController;
import com.MRSyc.config.MrConfig;
import com.MRSyc.constant.SysConstant;
import com.MRSyc.entity.TResources;
import com.MRSyc.entity.TUserExt;
import com.MRSyc.entity.TUserinfo;
import com.MRSyc.result.ResultData;
import com.MRSyc.service.ITResourcesService;
import com.MRSyc.service.ITRoleResourcesService;
import com.MRSyc.service.ITUserExtService;
import com.MRSyc.service.ITUserRoleService;
import com.MRSyc.service.ITUserinfoService;
import com.MRSyc.utils.ClientUtils;
import com.MRSyc.utils.MD5Util;
import com.MRSyc.utils.ToolKit;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import lombok.extern.slf4j.Slf4j;

/**
 *
 *
 *
 * @author Administrator
 */
@Slf4j
@Controller
@RequestMapping(value = "/")
public class SystemController extends BaseController {
	private ClientUtils client =new ClientUtils();
    @Autowired
    private ITUserinfoService userService;
    @Autowired
    private ITUserRoleService userRoleService;
    @Autowired
    private ITResourcesService resourcesService;
    @Autowired
    private ITRoleResourcesService roleResourcesService;
    @Autowired
    private ITUserExtService userExtServiceImpl;
    
    @Autowired
	private MrConfig mrconfig;



    private static final long PAGE_SIZE = 10L ;

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String defaultLogin(Model model) {
    	model.addAttribute("systemName",SysConstant.getConfigValueByName("systemName"));
        return "login/login";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String mainIndex(@RequestParam("userName") String userName, @RequestParam("password") String password,Model model){
        String md5Pass = MD5Util.getMD5(password);
        
        String loginRet = login(userName, md5Pass);
        //int num = 1/0 ;
        model.addAttribute("systemName",SysConstant.getConfigValueByName("systemName"));
        if("登录成功".equals(loginRet)){
            //获取菜单
            List<Map<String, Object>> menuList = getMenuList();
            
            for (Map<String, Object> map : menuList) {
				String tmp = map.get("resUrl")+ ":";
				List<TResources> rlist = (List<TResources>)map.get("subMenu");
				for (TResources r : rlist) {
					tmp = tmp + r.getResUrl()+ "||||";
				}
				System.out.println(tmp);
			}
            
            model.addAttribute("modulesList",menuList); 
            TUserinfo record = new TUserinfo();
            record.setUserName(userName);
            record.setPassword(md5Pass);
            QueryWrapper<TUserinfo> queryWrapper=new QueryWrapper<>();
            queryWrapper.setEntity(record);
            List<TUserinfo> findList = userService.list(queryWrapper);
            model.addAttribute("loginUser", findList.get(0));
            TUserExt userExt = new TUserExt();
            userExt.setUserId(findList.get(0).getId());
            QueryWrapper<TUserExt> wrapper=new QueryWrapper<>();
            wrapper.setEntity(userExt);
            userExt = userExtServiceImpl.getOne(wrapper);
            model.addAttribute("userExt",userExt);
            Subject subject = SecurityUtils.getSubject();
            Session session = subject.getSession();
            session.setAttribute("loginUserId", findList.get(0).getId());
            return "main/mainIndex";
        }else {
            model.addAttribute("loginRet",loginRet);
            return "login/login";
        }

    }

    
    
    //1.获取所有的菜单列表
    //2.根据userId 获取用户的角色，根据角色获取用户的资源，
    //3.根据用户对应的资源，设置用户的权限
    
    

    private List<Map<String,Object>> getMenuList(){
        List<TResources> allResources = resourcesService.list();
        //去除掉不必展示的 资源类型0显式资源1非显式资源  
        List<TResources> disPlayResources = new ArrayList<>();
        for(TResources res: allResources) {
        	if(res.getResType().intValue()==0) {
        		disPlayResources.add(res);
        	} 
        } 
        List<Map<String,Object>> modules = new ArrayList<>();
        disPlayResources.stream().forEach(r -> {
            int presKey = r.getPresKey();
            if(presKey == 0 ){// 模块名称
                try {
                    HashMap<String, Object> map = ToolKit.javaBeanToMap(r);
                    modules.add(map);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        modules.stream().forEach(map->{
            String resKey = map.get("resKey").toString();
            List<TResources> subMenu = new ArrayList<>();
            for (TResources r : disPlayResources) {
                String presKey = r.getPresKey().toString();
                if(presKey!=null && presKey.equals(resKey)){
                    subMenu.add(r);
                }
            }
            map.put("subMenu",subMenu);
        });
        return modules;
    }
    private String login(String userName,String password) {
        // 从SecurityUtils里边创建一个 subject
        Subject subject = SecurityUtils.getSubject();
        // 在认证提交前准备 token（令牌）
        UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
        // 执行认证登陆
        try {
            subject.login(token);     
        } catch (UnknownAccountException uae) {
            return "未知账户";
        } catch (IncorrectCredentialsException ice) {
            return "密码不正确";
        } catch (LockedAccountException lae) {
            return "账户已锁定";
        } catch (ExcessiveAttemptsException eae) {
            return "用户名或密码错误次数过多";
        } catch (AuthenticationException ae) {
            return "用户名或密码不正确！";
        }
        if (subject.isAuthenticated()) {
        	Map<String,String> params=new HashMap<>();
        	params=new HashMap<>();
	    	params.put("client_id", mrconfig.getClient_id());
	    	params.put("client_secret", mrconfig.getClient_secret());
	    	params.put("grant_type", mrconfig.getGrant_type());
	    	params.put("username", mrconfig.getUsername());
	    	params.put("password", mrconfig.getPassword());
	    	String flg=client.getToken(mrconfig.getLoginUrl(), params);
            return "登录成功";
        } else {
            token.clear();
            return "登录失败";
        }
    }

    
    
    /***
     * 根据key 查询是否有权限
     * @param keys
     * @return
     */
    @SuppressWarnings("unchecked")
	@RequestMapping(value="/validatePermisson", method = RequestMethod.POST)
    @ResponseBody
    public ResultData<Map<String,Object>> validatePermisson(@RequestParam("keys[]") String[] keys) {
    	log.info(keys.toString()); 
        Subject subject = SecurityUtils.getSubject(); 
        Map<String,Object> permissionMap = new HashMap<>(); 
    	for(String k:keys) {
    		  boolean permitted = subject.isPermitted(k);
    		  permissionMap.put(k, permitted);
    	}
		return ResultData.genSuccessResultData(permissionMap);
    	
    }


}
